//
//  SettingViewController.m
//  cherryPicker
//
//  Created by Young Soo Yun on 12. 1. 2..
//  Copyright (c) 2012 Happy. All rights reserved.
//

#import "SettingViewController.h"

#import "Options.h"
#import "ControlUtil.h"

@implementation SettingViewController

@synthesize _tableDic;
@synthesize _dicKey;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //
    
    NSArray* autoSetting = [[NSArray alloc] initWithObjects:@"실행시 자동 SMS 입력창", @"자동 입력 팝업", nil];
    NSArray* info = [[NSArray alloc] initWithObjects:@"가이드", @"개발자 문의",
                     [NSString stringWithFormat:@"버전 정보                                Ver.%@",
                      [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]], nil];
    
    self._tableDic =[[NSDictionary alloc]
                initWithObjectsAndKeys:autoSetting, @"자동완성", info, @"정보", nil];
    
    self._dicKey = [[_tableDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
    
    _numOfSection = [_dicKey count];
    
    G__SAFE_FREE(autoSetting);
    G__SAFE_FREE(info);
    
    //
    _isAutoModal = ([[Options getValue:OptionUser1 valueName:@"modal"] isEqualToString:@"1"])?YES:NO;
    _isAutoPopup = ([[Options getValue:OptionUser1 valueName:@"popup"] isEqualToString:@"1"])?YES:NO;
    
    _topMenuVC = [[TopMenuViewController alloc] initWithNibName:@"TopMenuViewController" bundle:nil];
	[_topMenuVC initWithMenuType:CHERRY_MENU_SETTING];
    [_topMenuVC setVController:self];
	[_topMenuVC set_delegate:self];
    [_topMenuVC initTopMenuBtnType:TOP_LEFT_BACK right:TOP_RIGHT_NONE];
    
    [self.view addSubview:_topMenuVC.view];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	G__SAFE_FREE(_topMenuVC);
    
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        switch (indexPath.row) {
            case 0:{
                // go to my blog
                NSString *urlString=[NSString stringWithFormat:@"http://m.blog.naver.com/kai1945"];
                NSURL *url=[NSURL URLWithString:urlString];
                [[UIApplication sharedApplication] openURL:url];
                
                break;
            }
            case 1:{
                // email
                
                MFMailComposeViewController *mailsome=[[MFMailComposeViewController alloc] init];
                mailsome.mailComposeDelegate=self;
                if([MFMailComposeViewController canSendMail]){
                    [mailsome setToRecipients:[NSArray arrayWithObjects:@"kai1945@naver.com", nil]];
                    [mailsome setSubject:@"[CP]"];
                    [mailsome setMessageBody:nil isHTML:NO];
                    [self presentModalViewController:mailsome animated:YES];
                }
                
                break;
            }
        }
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return [self._dicKey count];
}

- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
	return [self._dicKey objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)table
 numberOfRowsInSection:(NSInteger)section {
    NSArray *data =[self._tableDic objectForKey:
                    [self._dicKey objectAtIndex:section]];
	return data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
		 cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell * cell = [tableView
							  dequeueReusableCellWithIdentifier:@"cell"];
	
	if(cell == nil) {
		cell = [[[UITableViewCell alloc]
				 initWithStyle:UITableViewCellStyleValue1
				 reuseIdentifier:@"cell"] autorelease];
	}
    
    NSArray *data =[self._tableDic objectForKey:
						[self._dicKey objectAtIndex:[indexPath section]]];
    cell.textLabel.text =[data objectAtIndex:indexPath.row];
    
    if (indexPath.section == 0) {
        cell.accessoryView =[[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
        [(UISwitch *)cell.accessoryView setOn:(indexPath.row == 0)?_isAutoModal:_isAutoPopup];
        [(UISwitch *)cell.accessoryView addTarget:self
                                           action:(indexPath.row == 0)?@selector(changeModalState:):@selector(changePopupState:)
                                 forControlEvents:UIControlEventValueChanged];
    }else{
        
        if (indexPath.row != 2) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
	
	return cell;
}

#pragma mark - MFMailComposeViewControllerDelegate

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    [self dismissModalViewControllerAnimated:YES];
    
    if(result == MFMailComposeResultFailed){
        [ControlUtil showAlertCaution:@"메일 전송 실패" body:@"메일을 전송 할 수 없습니다." delegate:nil];
    }
}

#pragma mark -

- (void) changeModalState: (id) sender
{
	UISwitch *senderSwitcher = (UISwitch*) sender;
	_isAutoModal = (BOOL) senderSwitcher.isOn;
    
    [Options setValue:OptionUser1 valueName:@"modal" value:(_isAutoModal)?@"1":@"0"];
    
}

- (void) changePopupState: (id) sender
{
	UISwitch *senderSwitcher = (UISwitch*) sender;
	_isAutoPopup = (BOOL) senderSwitcher.isOn;
    
    [Options setValue:OptionUser1 valueName:@"popup" value:(_isAutoPopup)?@"1":@"0"];
    
}

@end
